﻿<style>
    .box2 {
        background-color: rgb(51,51,51);
        color: #ccc;
        line-height: 40px;
        padding: 0 14px;
        border: 1px #ccc solid;
        border-radius: 5px;
        text-indent: 1em;
        margin: 15px 0;
    }

        .box2 input:focus {
            outline: none;
        }

    .box2_input1 {
        width: 320px;
        color: white;
        border: none;
        background-color: rgb(51,51,51);
        height: 22px;
        font-size: 15px;
        margin: 0 0 0 20px;
    }

    .upload-container {
        color: #fff;
        font-family: Arial, sans-serif;
        position: relative;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    input[type="file"] {
        display: none;
    }

    .upload-pic {
        position: absolute;
        display: none;
        width: 81px;
        height: 81px;
        border-radius: 50%;
        object-fit: cover;
    }

    .upload-btn {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        border: 1px dotted #fff;
    }

    .fail {
        position: absolute;
        top: 0;
        left: 50%;
        transform: translateX(-50%);
        z-index: 999999999999;
        height: 80px;
        overflow: hidden;
    }
    html{
        width:99% !important;
        height:99% !important;
    }
</style>
<div class="alert fail" id="liveAlertPlaceholder"></div>
<div class="container-fluid">
    <div class="row main">
        <div class="col-1 left-nav">
            <div class="avatar">
                <img src="~/image/default.jpg" />
            </div>
            <ul class="nav flex-column">
                <li class="nav-item active" data-index="" onclick="window.location = '/chat/'">
                    <i class="bi bi-chat-dots"></i>
                </li>
                <li class="nav-item" onclick="window.location = '/chat/contact'">
                    <i class="bi bi-person"></i>
                </li>
                <li class="nav-item" data-bs-toggle="modal" data-bs-target="#exampleModal">
                    <i class="bi bi-gear"></i>
                </li>
            </ul>
        </div>

        <div class="col-3 f-list">
            <div class="f-list-col">

            </div>
        </div>
        <div class="col-8 chat-main">
            <img class="pic-qq" src="~/image/nochat-bg.png" />
            <div class="content">
                <div class="content-header">
                    接收人
                </div>
                <div class="content-main">

                </div>
                <div class="content-footer">
                    <div class="icons">
                        <i class="bi bi-camera-video" data-bs-toggle="modal" data-bs-target="#exampleModal6" onclick="openlaidian()"></i>
                        <label for="pic_up">
                            <i class="bi bi-file-image"></i>
                        </label>
                        <input id="pic_up" class="pic_up" type="file" accept="image/*" />
                    </div>
                    <textarea class="ipt" rows="5"></textarea>
                    <button class="btn btn-primary send">发送</button>
                </div>
            </div>
        </div>

    </div>
</div>

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="background-color:rgb(27,27,27)">
            <div class="modal-header">
                <h1 class="modal-title fs-5" style="color:#fff" id="exampleModalLabel">个人资料</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="color:#fff"></button>
            </div>
            <form class="modal-body">
                <div class="upload-container">
                    <label for="hxd" class="upload-btn"></label>
                    <input id="hxd" class="upload" type="file" accept="image/*" />
                    <img class="upload-pic" />
                </div>
                <div class="box2">昵称<input tupe="text" class="box2_input1 nc" /></div>
                <div class="box2">年龄<input tupe="text" class="box2_input1 age" /></div>
                <div class="box2">签名<input tupe="text" class="box2_input1 qm" /></div>
                <div class="box2">密码<input tupe="text" class="box2_input1 pwd" /></div>
                <div style="display:flex;justify-content:flex-end">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal" aria-label="Close">取消</button>
                    <button style="margin-left:15px;" type="button" class="btn btn-outline-secondary sumbit">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="exampleModal6" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="background-color:rgb(27,27,27);width:560px;height:480px;">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel" style="color:#fff">视频聊天</h1>
                <button type="button" data-bs-dismiss="modal" style="color: #fff; background-color: rgb(27,27,27);border:none;" onclick="closeliandian()">X</button>
            </div>
            <div class="modal-body" style="color: #fff; padding: 0px">
                <div class="chat-video" style="width: 386px; height: 336px; margin: auto; margin-top: 20px; overflow: hidden; background: url(/image/loading.gif); background-repeat: no-repeat; background-position: center center; background-size: 20%; ">
                    
                </div>
            </div>
        </div>
    </div>
</div>
<script src="~/Scripts/jquery-3.7.1.js"></script>
<script src="~/Scripts/jquery.signalR-2.4.3.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>


        var chat = $.connection.chatHub;


        chat.client.close = function () {
            alert("close");
            $.connection.hub.stop();
        };

        chat.client.refresh = function () {
            setTimeout(() => {
                reflow();
                reflowFriend();
            }, 100);

        };


        function SendAction() {

            let msg = $('.ipt').val().trim()
            if (msg == '') {
                return;
            }

            var formData = new FormData();
            formData.append('SenderID', u_data.UserID);
            formData.append('ReceiverID', FriendId);
            formData.append('MessageText', msg);
            formData.append('MessageType', 0);

            // 发送POST请求
            fetch('/api/sendChatMessage', {
                method: 'POST',
                body: formData,
                headers: {
                    token: localStorage.getItem('token')
                }
            })
                .then(function (response) {
                    if (response.ok) {
                        return response.json();
                    } else {
                        throw new Error('请求失败');
                    }
                })
                .then(function (data) {
                    console.log(data);
                })
                .catch(function (error) {
                    console.error(error);
                });


            chat.server.refreshFriend(FriendId);

        }


        function SendImageAction(f) {

            var formData = new FormData();
            formData.append('SenderID', u_data.UserID);
            formData.append('ReceiverID', FriendId);
            formData.append('MessageText', f);
            formData.append('MessageType', 1);

            // 发送POST请求
            fetch('/api/sendChatMessage', {
                method: 'POST',
                body: formData,
                headers: {
                    token: localStorage.getItem('token')
                }
            })
                .then(function (response) {
                    if (response.ok) {
                        return response.json();
                    } else {
                        throw new Error('请求失败');
                    }
                })
                .then(function (data) {
                    console.log(data);
                })
                .catch(function (error) {
                    console.error(error);
                });


            chat.server.refreshFriend(FriendId);

        }
        function sendPic() {
            var file = this.files[0];
            if (file) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    upload_pic.setAttribute("src", e.target.result)
                    upload_pic.style.display = 'block'
                }
                reader.readAsDataURL(file);
                console.log(file)

                var formData = new FormData();
                formData.append("imageFile", file);

                fetch("/api/UploadFile", {
                    method: "POST",
                    headers: {
                        'token': localStorage.getItem("token")
                    },
                    body: formData
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.Code == 200) {
                            SendImageAction(data.FileNmae)
                            return
                        } else {
                            Alert("图片上传失败", 'danger')
                        }
                    })
                    .catch(error => {
                        console.log(error)
                        Alert("图片上传错误", 'danger')
                    });

            }
        }

        const pic_up = document.querySelector("#pic_up")
        pic_up.addEventListener('change', sendPic)


        $.connection.hub.start().done(function () {
            $('.ipt').keydown(function (event) {
                if (event.which === 13) {
                    SendAction();
                    setTimeout(() => {
                        $('.ipt').val('')
                    })
                }
            })
            $('.send').click(SendAction);
            chat.server.auth(localStorage.getItem("token"));
        });




    // This optional function html-encodes messages for display in the page.
    function fun(value) {
        alert(value);
    }


    var u_data;
    var FriendId;


    function closeliandian() {
       
        document.querySelector('.chat-video').innerHTML = ``;

        console.log('关闭来电！')
    }

    function openlaidian() {

        console.log(document.querySelector('.modal-body'))

        var room = '';
        if (u_data.UserID < FriendId) {
            room = u_data.UserID + 'u' + FriendId
        } else {
            room = room = FriendId + 'u' + u_data.UserID 
        }

        document.querySelector('.chat-video').innerHTML = `<iframe src="https://tokbox.com/embed/embed/ot-embed.js?embedId=26958d33-c592-46c3-8fda-7b5e2abebcf6&room=${room}&iframe=true" width=400 height=350  allow="microphone; camera"></iframe>`
        console.log("打开来电");

        document.body.className = 'modal-open'
        document.querySelector("#exampleModal6").classList.add('show')
        document.querySelector("#exampleModal6").style.display = 'block'

    }



    const upload = document.querySelector(".upload")
    const upload_pic = document.querySelector(".upload-pic")
    const upload_btn = document.querySelector(".upload-btn")


    upload_pic.addEventListener('click', () => {
        upload_btn.click()
    })

    upload.addEventListener('change', up);
    function up() {
        var file = this.files[0];
        if (file) {
            var reader = new FileReader();
            reader.onload = function (e) {
                upload_pic.setAttribute("src", e.target.result)
                upload_pic.style.display = 'block'
            }
            reader.readAsDataURL(file);
            console.log(file)

            var formData = new FormData();
            formData.append("imageFile", file);

            fetch("/api/UploadFile", {
                method: "POST",
                headers: {
                    'token': localStorage.getItem("token")
                },
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.Code === 200) {
                        u_data.AvatarImageURL = data.FileNmae
                    } else {
                        Alert("图片上传失败",'danger')
                    }
                })
                .catch(error => {
                    Alert("图片上传错误",'danger')
                });

        }
    }



    const nc = document.querySelector(".nc")
    const age = document.querySelector(".age")
    const qm = document.querySelector(".qm")
    const pwd = document.querySelector(".pwd")
    const sumbit = document.querySelector(".sumbit")

    @* 更新好友列表 *@
    function reflowFriend() {

        console.log('f_id', FriendId)

        fetch("/api/getFriendAndLastMessage", {
            method: "post",
            headers: {
                'token': localStorage.getItem("token")
            }
        }).then((data) => data.json())
            .then((data) => {

                u_data = data.User;
                @*
                    更改用户头像
                    *@
                    avatar.setAttribute("src", data.User.AvatarImageURL)
                f_list.innerHTML = '';
                console.log(data.FriendsAndLastMessage)

                for (let item of data.FriendsAndLastMessage) {
                    console.log(item)
                    f_list.innerHTML += `
                    <div class="f-list-col-item ${item.friend.UserID == FriendId ? 'active' : ''}" data-UserID=${item.friend.UserID}  onclick="paint(this)">
                        <div class="pic">
                            <img src="${item.friend.AvatarImageURL}"/>
                        </div>
                        <div class="msg">
                            <div class="msg-top">
                              ${item.friend.UserName}
                             </div>
                             <div class="msg-bottom">
                                ${item.LastMessage ? (item.LastMessage.MessageType == 1 ? '[图片]': item.LastMessage.MessageText): '[还没有开始聊天哦]'}
                            </div>
                        </div>
                        <div class="time">
                            ${item.LastMessage ? YMD(extractNumbers(item.LastMessage.Timestamp)) :''}
                        </div>
                    </div>`
                }

                nc.value = u_data.UserName
                age.value = u_data.Age
                qm.value = u_data.PersonalSignature
                upload_pic.setAttribute("src", u_data.AvatarImageURL)
                upload_pic.style.display = 'block'
            })
    }
    @* 更新聊天 *@
    function reflow() {
        if (!FriendId) {
            console.log('return ')
            return;
        }

        const content = document.querySelector(".chat-main .content")

        content.style.top = 0
        content.style.left = 0


        const content_main = document.querySelector(".chat-main .content-main")
        const content_header = document.querySelector(".content-header")

        var getUserByUserIdFromData = new FormData();
        getUserByUserIdFromData.append('userId', FriendId);
        var f_data;
        @* 获取好友信息 *@
            fetch("/api/getUserByUserId", {
                method: "post",
                headers: {
                    'token': localStorage.getItem("token")
                },
                body: getUserByUserIdFromData
            }).then(data => data.json())
                .then(data => {
                    f_data = data.User
                })

        var getChatMessagesWithFriendFromData = new FormData();
        getChatMessagesWithFriendFromData.append('FriendId', FriendId);
        @* 更新聊天内容 *@
        fetch("/api/getChatMessagesWithFriend", {
            method: "post",
            headers: {
                'token': localStorage.getItem("token")
            },
            body: getChatMessagesWithFriendFromData
        }).then(data => data.json())
            .then(data => {

                content_header.innerHTML = f_data.UserName;
                content_main.innerHTML = ''
                for (var chatMessage of data.ChatMessages) {

                    var str= `
                         <div class="${u_data.UserID == chatMessage.SenderID ? 'flex-reverse' : 'flex'}">
                        <div class="time">${YMD(extractNumbers(chatMessage.Timestamp))}</div>
                        <img src="${u_data.UserID == chatMessage.SenderID ? u_data.AvatarImageURL : f_data.AvatarImageURL}" class='avatar'/>
                    `
                    if (chatMessage.MessageType == 0) {
                        str += ` <div class="message">${chatMessage.MessageText}</div ></div >`
                    } else {
                        str +=
                           ` <div style="margin-right:6px;">
                                <img class='www' style="height:200px;object-fit:cotain;border-radius:5px;" src="${chatMessage.MessageText}"/>
                             </div ></div >`
                    }

                    content_main.innerHTML += str;
                    content_main.scrollTo(0, content_main.scrollHeight)
                }
            })

    }

    sumbit.addEventListener('click', () => {
        const formdata = new FormData()

        formdata.append('UserName', nc.value)
        formdata.append('Age', age.value)
        formdata.append('PersonalSignature', qm.value)
        formdata.append('Password', pwd.value)
        formdata.append('AvatarImageURL', u_data.AvatarImageURL)

        fetch("/api/updateUserByUserId", {
            method: "POST",
            headers: {
                'token': localStorage.getItem("token")
            },
            body: formdata
        })
            .then(response => response.json())
            .then(data => {
                if (data.Code === 200) {

                    reflow();
                    reflowFriend();

                    Alert("修改成功！", 'success')


                } else {
                    Alert("什么也没有发生",'danger')
                }
            })
            .catch(error => {
                alert("error",'error')
            });


    })

    function YMD(milliseconds) {
        milliseconds = +milliseconds
        // 创建一个新的Date对象，使用传入的毫秒数
        var date = new Date(milliseconds);

        // 获取年份、月份、日期、小时和分钟
        var year = date.getFullYear();
        var month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要+1
        var day = String(date.getDate()).padStart(2, '0');
        var hours = String(date.getHours()).padStart(2, '0');
        var minutes = String(date.getMinutes()).padStart(2, '0');

        // 构造并返回格式化的日期字符串
        return `${year}年${month}月${day}日 ${hours}:${minutes}`;
    }

    function extractNumbers(str) {
        let matches = str.match(/\d+/g);
        return matches ? matches.join("") : "";
    }

    const avatar = document.querySelector(".avatar img")
    const f_list = document.querySelector(".f-list-col")


    function paint(s) {
        var qq_bg = document.querySelector(".chat-main .pic-qq")
        const content = document.querySelector(".chat-main .content")
        var f_items = document.getElementsByClassName("f-list-col-item")
        for (let i = 0; i < f_items.length; i++) {
            f_items[i].classList.remove('active')
        }
        s.classList.add('active')
        qq_bg.style.display = 'none'


        @* 更新选中用户id *@
        FriendId = parseInt(s.getAttribute("data-UserID"))
        reflow()
    }

    @* 是否登陆 *@
    function isLogin() {
        fetch('/api/auth', {
            method: "post",
            headers: {
                'token': localStorage.getItem("token")
            }
        }).then((data) => {
            if (data.status == 401) {
                window.location.href = '/chat/login'
            }
        })
    }

    function GetQuery() {
        // 获取地址栏上的查询字符串
        var queryString = window.location.search;

        // 创建URLSearchParams对象
        var params = new URLSearchParams(queryString);

        // 获取特定参数的值
        var paramValue = params.get('f_id');

        FriendId = paramValue
    }




    window.onload = function () {
        var items = document.querySelectorAll(".nav li")
        console.log(items)
        for (let i = 0; i < items.length; i++) {
            items[i].addEventListener('click', () => {
                for (let i = 0; i < items.length; i++) {
                    items[i].classList.remove('active')
                }
                items[i].classList.add('active')
            })
        }
    }

    const alertPlaceholder = document.getElementById('liveAlertPlaceholder')
    const Alert = (message, type) => {
        const wrapper = document.createElement('div')
        wrapper.innerHTML = [
            `<div class="alert alert-${type} alert-dismissible" role="alert">`,
            `   <div style="margin-right:40px;">${message}</div>`,
            '   <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
            '</div>'
        ].join('')

        alertPlaceholder.append(wrapper)

        setTimeout(() => {
            wrapper.remove()
        }, 2000)
    }

    isLogin()
    GetQuery()
    reflowFriend();
    reflow();
</script>
